package com.asia5b.a5mall.order.activity

import androidx.recyclerview.widget.LinearLayoutManager
import android.text.TextUtils
import android.view.View
import androidx.lifecycle.Observer
import com.alibaba.android.arouter.facade.annotation.Route
import com.asia5b.a5bmall.resource.ActCons
import com.asia5b.a5bmall.same.fragment.OrderCouponDF
import com.asia5b.a5mall.middleware.base.SimpleActivity
import com.asia5b.a5mall.middleware.config.Asia5bPayUtils
import com.asia5b.a5mall.middleware.event.PlaceSelectEvent
import com.asia5b.a5mall.middleware.event.SelectAddressChange
import com.asia5b.a5mall.middleware.logic.viewmodel.order.OrderPlaceActivityVM
import com.asia5b.a5mall.middleware.model.bean.*
import com.asia5b.a5mall.middleware.model.cart.CartAllModel
import com.asia5b.a5mall.middleware.model.cart.CartPriceModel
import com.asia5b.a5mall.middleware.model.cart.TransModel
import com.asia5b.a5mall.middleware.model.member.AddressModel
import com.asia5b.a5mall.middleware.model.member.HouseModel
import com.asia5b.a5mall.middleware.model.member.UserCouponModel
import com.asia5b.a5mall.middleware.model.order.*
import com.asia5b.a5mall.middleware.model.bean.GlobalState
import com.asia5b.a5mall.middleware.model.shop.AbsShopModel
import com.asia5b.a5mall.middleware.utils.*
import com.asia5b.a5mall.order.R
import com.asia5b.a5mall.order.adapter.OrderPlacePriceAdapter
import com.asia5b.a5mall.order.adapter.OrderPlaceShopAdapter
import com.asia5b.a5mall.order.databinding.ActivityOrderplaceBinding
import kotlinx.android.synthetic.main.activity_orderplace.*
import kotlinx.android.synthetic.main.item_orderplace_remark.*
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode

/**
 * Created by zhangyuncai on 2020/1/6.
 * 提交订单
 */
@Route(path = ActCons.OrderPlaceActivity)
class OrderPlaceActivity : SimpleActivity<OrderPlaceActivityVM, ActivityOrderplaceBinding>() {
    override val viewModelClazz: Class<OrderPlaceActivityVM>
        get() = OrderPlaceActivityVM::class.java

    override fun getDataBinding(): ActivityOrderplaceBinding {
        return ActivityOrderplaceBinding.inflate(layoutInflater)
    }

    override var sIsDark = true

    //商品列表
//    val goods = arrayListOf<CartMultiItemEntity>()
//    val goodsAdapter by lazy { OrderPlaceGoodsAdapter(goods) }
//    val goodsRecyclerView by lazy { rv_orderplace_goods }

    val goods2 = arrayListOf<AbsShopModel>()
    val goodsAdapter2 by lazy { OrderPlaceShopAdapter(goods2) }
    val goodsRecyclerView2 by lazy { rv_orderplace_goods2 }

    //价格列表
    var mCartPriceModel = CartPriceModel()
    val priceList = arrayListOf<OrderPlacePriceMenuBean>()
    val priceAdapter by lazy { OrderPlacePriceAdapter(priceList) }
    val priceRecyclerView by lazy { rv_orderplace_price }

    //仓库列表
    var houseModelList = arrayListOf<HouseModel>()

    //国际运输方式
    var transModelList = arrayListOf<TransModel>()

    //支付方式方式
    var orderPayBeanList = OrderPayBean.getOrderPayBeans()

    //立即购买(true/商品详情购买,false/购物车购买)
    var isBuyNow = false

    //请求商品等详情需要用到的接口
    val map = mutableMapOf<String, Any>()


    override fun initView() {
        isBuyNow = intent.getBooleanExtra("isBuyNow", false)
        mViewModel.isBuyNow = isBuyNow
        //地区id
        map["region_id"] = 0
        map["city_id"] = 0
        //仓库
        map["house_id"] = 0
        //运输方式id
        map["goodscata_id"] = 0
        //地址id
        map["address_id"] = 0
        //付款方式
        map["payment_type"] = "ONLINE"
        //订单支付方式
        map["payment_num"] = 1
        //创建订单来源
        map["client"] = "WAP"
        //购物方式
        map["way"] = mViewModel.getWay()
//        goodsRecyclerView.run {
//            layoutManager = LinearLayoutManager(mActivity)
//            adapter = goodsAdapter
//        }
        goodsRecyclerView2.run {
            layoutManager = LinearLayoutManager(mActivity)
            adapter = goodsAdapter2
        }
        priceRecyclerView.run {
            layoutManager = LinearLayoutManager(mActivity)
            adapter = priceAdapter
        }

        setCouponView(null)
        setHouseView(null)
        setTransferView(null)
        setPayView(orderPayBeanList.getOrNull(0))

        getOrderDetail()
    }

    fun getOrderDetail() {
        mViewModel.getOrderDetail(map)
    }

    override fun initEvent() {

        /**
         * 选择仓库方式
         */
        ll_orderplace_house.setOnClickListener {
//            showSelectDialog(SelectType.house)
            startPlaceSelectActivity(SelectType.house)
        }
        /**
         * 选择运输方式
         */
        ll_orderplace_transfer.setOnClickListener {
//            showSelectDialog(SelectType.intertrans)
            startPlaceSelectActivity(SelectType.intertrans)
        }
        /**
         * 选择支付方式
         */
        ll_orderplace_pay.setOnClickListener {
//            showSelectDialog(SelectType.pay)
            startPlaceSelectActivity(SelectType.pay)
        }
        /**
         * 提交
         */
        onFilterDoubleClick(bt_orderplace_submit, View.OnClickListener {
            Asia5bPayUtils.getAuthorization(mActivity as SimpleActivity<*, *>, true) { isCanSkip ->
                if (isCanSkip) {
                    if (!TextUtils.isEmpty(tv_orderplace_remark.text.toString().trim())) {
                        map.put("remark", tv_orderplace_remark.text.toString().trim())
                    }
                    mViewModel.createOrder(map)
                }
            }

        })
        /**
         * 备注保存
         */
        tv_orderplace_remark_save.setOnClickListener {
            val remark = tv_orderplace_remark.text.toString()
            mViewModel.setRemark(remark)
        }
        val onClickListener = View.OnClickListener {
            push(ActCons.AddressListActivity, {
                it.withBoolean("order", true)
            }, requstCode = GlobalState.ORDER_CREATE_ADDRESS)
        }
        /**
         * 修改地址
         */
        ll_orderplace_address.setOnClickListener(onClickListener)

        //选择优惠券
        ll_orderplace_coupon.setOnClickListener {
            val couponTempList = arrayListOf<UserCouponModel>()
            couponList?.forEach {
                if (it.enable == 1) {
                    couponTempList.add(it)
                }
            }
            if (couponTempList.size > 0) {
                val orderCouponDF = OrderCouponDF().run {
                    mDatas.addAll(couponTempList)
                    this
                }
                orderCouponDF.show(supportFragmentManager, "OrderCouponDF")
                orderCouponDF.setSureClick<UserCouponModel> {
                    var memberCouponId = 0
                    if (it.selected != 1) {
                        memberCouponId = it.member_coupon_id
                    }
                    mViewModel.userCoupon(it.seller_id, memberCouponId, isBuyNow)
                }
            }
        }
    }

    override fun initData() {
    }

    /**
     * 采用另一种UI展示选择
     */
    fun startPlaceSelectActivity(type: SelectType) {
        when (type) {
            //国际运输方式
            SelectType.intertrans -> {
                var selectText = ll_orderplace_transfer.selectModel?.run {
                    this as SelectText
                }?.getText()
                PlaceSelectActivity.startPlaceSelectActivity(mActivity, type, transModelList, "${selectText}")
            }
            //仓库
            SelectType.house -> {
                var selectText = ll_orderplace_house.selectModel?.run {
                    this as SelectText
                }?.getText()
                PlaceSelectActivity.startPlaceSelectActivity(mActivity, type, houseModelList, "${selectText}")

            }
            //支付
            SelectType.pay -> {
                var selectText = ll_orderplace_pay.selectModel?.run {
                    this as SelectText
                }?.getText()
                PlaceSelectActivity.startPlaceSelectActivity(mActivity, type, orderPayBeanList, "${selectText}")
            }
        }

    }

    override fun startObserver() {
        mViewModel.setAddressViewLiveData.observe(this, Observer {
            setAddressView(it)
        })
        mViewModel.setHouseListLiveData.observe(this, Observer {
            setHouseList(it)
        })
        mViewModel.setTransferListLiveData.observe(this, Observer {
            setTransferList(it)
        })
        mViewModel.setParamsViewLiveData.observe(this, Observer {
            setParamsView(it)
        })
        mViewModel.setPriceViewLiveData.observe(this, Observer {
            setPriceView(it)
        })
        mViewModel.userCouponResultLiveData.observe(this, Observer {
            userCouponResult()
        })
        mViewModel.createOrderResultLiveData.observe(this, Observer {
            createOrderResult(it)
        })
    }

    /**
     * 设置地址
     */
    fun setAddressView(addressModel: AddressModel) {
        ll_orderplace_address.addressModel = addressModel
    }

    /**
     * 仓库
     */
    fun setHouseList(housesModel: ArrayList<HouseModel>?) {
        houseModelList.clear()
        if (!housesModel.isNullOrEmpty()) {
            houseModelList.addAll(housesModel)
        }
        setHouseView(houseModelList.getOrNull(0))
    }

    /**
     * 设置仓库地址
     */
    fun setHouseView(houseModel: HouseModel?) {
        val orderPlaceMenuBean = OrderPlaceMenuBean(OrderPlaceItemEntity.OrderPlace_Houce,
                getString(R.string.选择仓库), getString(R.string.暂无可使用))
        houseModel?.run {
            orderPlaceMenuBean.value = this.house_name
        }
        ll_orderplace_house.selectModel = houseModel
        ll_orderplace_house.setMenuBean(orderPlaceMenuBean)
    }


    /**
     * 运输方式
     */
    fun setTransferList(transportations: ArrayList<TransModel>?) {
        transModelList.clear()
        if (!transportations.isNullOrEmpty()) {
            transModelList.addAll(transportations)
        }
        setTransferView(transModelList.getOrNull(0))
    }

    /**
     * 国际运输方式
     */
    fun setTransferView(transModel: TransModel? = null) {
        val orderPlaceMenuBean = OrderPlaceMenuBean(OrderPlaceItemEntity.OrderPlace_Transtype,
                getString(R.string.国际运输方式), getString(R.string.暂无可使用))
        if (transModel != null) {
            orderPlaceMenuBean.value = "${transModel?.goodsName}"
        }
        ll_orderplace_transfer.selectModel = transModel
        ll_orderplace_transfer.setMenuBean(orderPlaceMenuBean)
    }


    /**
     * 设置支付方式
     */
    fun setPayView(orderPayBean: OrderPayBean?) {
        val orderPlaceMenuBean = OrderPlaceMenuBean(OrderPlaceItemEntity.OrderPlace_Houce,
                getString(R.string.支付类型), getString(R.string.极速发货))
        orderPayBean?.run {
            orderPlaceMenuBean.value = payName
            ll_orderplace_transfer.visibility = (payId == 1).judge(View.VISIBLE, View.GONE)
        }
        ll_orderplace_pay.selectModel = orderPayBean
        ll_orderplace_pay.setMenuBean(orderPlaceMenuBean)
    }


    //可使用的优惠券
    var couponList: ArrayList<UserCouponModel>? = null

    /**
     * 商品
     */
    fun setGoodsView(cartAllModel: CartAllModel) {
        goods2.clear()
        cartAllModel.cart_list?.forEach { cartShopModel ->
            if (true) {
                goods2.add(cartShopModel)
            }
            if (false) {
                //添加店铺信息
//                goods.add(cartShopModel)
//
//                //店家商品列表
//                cartShopModel?.absShopGoodsList?.forEach { cartGoodsItemViewModel ->
//                    goods.add(cartGoodsItemViewModel)
//                }
//                //添加分割线
//                goods.add(CartHolderBean())
            }

            //可使用的优惠券
            couponList = cartShopModel.absShopCouponList

        }
//        goodsAdapter.notifyDataSetChanged()
        goodsAdapter2.notifyDataSetChanged()


    }

    /**
     * 支付/备注
     * @param orderCheckParamsModel 上次购买的一些记录
     */
    fun setParamsView(orderCheckParamsModel: OrderCheckParamsModel?) {
        var remark = ""
        orderCheckParamsModel?.run {
            remark = remark ?: ""
        }
        tv_orderplace_remark.setText(remark)
    }

    /**
     * 优惠券
     */
    fun setCouponView(couponModel: UserCouponModel? = null) {
        var value = getString(R.string.暂无可使用)
        couponModel?.let { item ->
            value = CurrencyPriceBuilder3().run {
                price = item.amount
                priceList = item.amount_list
                String.format(getString(R.string.优惠折扣_数), "${buildPriceText()}")
            }
        }
        val orderPlaceMenuBean = OrderPlaceMenuBean(OrderPlaceItemEntity.OrderPlace_Transtype, getString(R.string.优惠券), value)
        ll_orderplace_coupon.setMenuBean(orderPlaceMenuBean)

    }


    /**
     * 价格
     */
    fun setPriceView(cartAllModel: CartAllModel) {
        priceList.clear()
        val cartPriceModel = cartAllModel.total_price ?: CartPriceModel()

        setGoodsView(cartAllModel)

        cartPriceModel?.run {
            mCartPriceModel = this
            //商品总金额
            priceList.add(OrderPlacePriceMenuBean(OrderPlaceItemEntity.OrderPlace_OrderSumprice, getString(R.string.商品金额), original_price, original_price_list))
            //国内运费
            priceList.add(OrderPlacePriceMenuBean(OrderPlaceItemEntity.OrderPlace_LocalTrans, getString(R.string.国内运费), freight_price, freight_price_list, 1))
            //国际运费
            priceList.add(OrderPlacePriceMenuBean(OrderPlaceItemEntity.OrderPlace_InterTrans, getString(R.string.国际运费), international_price, international_price_list, 1))
            //折扣优惠
            priceList.add(OrderPlacePriceMenuBean(OrderPlaceItemEntity.OrderPlace_Discount, getString(R.string.折扣优惠), coupon_price, coupon_price_list, 2))
            //合计
            priceList.add(OrderPlacePriceMenuBean(OrderPlaceItemEntity.OrderPlace_Sumprice, getString(R.string.应付金额), total_price, total_price_list))
            bt_orderplace_submit.isEnabled = (total_price <= 0).judge(false, true)
            priceAdapter.notifyDataSetChanged()
            //合计
            CurrencyPriceBuilder3().run {
                textView = tv_orderplace_price
                price = total_price
                priceList = total_price_list
                build14_18()
            }

            var selectCoupon: UserCouponModel? = null
            couponList?.forEach {
                if (it.enable == 1 && it.selected == 1) {
                    selectCoupon = it
                }
            }
            setCouponView(selectCoupon)


        }

        cartAllModel?.cart_list

//        setGoodsView(cartAllModel)
    }

    fun setAddressResult(addressModel: AddressModel) {

    }

    /**
     * 创建订单
     */
    fun createOrderResult(tradeSerialNo: String?) {
        var pay = OrderPayModel()
        pay.paymentType = GlobalState.PAY_ONLINE
        pay.payPrice = mCartPriceModel.total_price
        pay.tradeType = TradeType.Trade
//        if (TextUtils.equals("${map["payment_num"]}", "2")) {
//            pay.tradeType = TradeType.Diff
//        } else {
//        }
        pay.sn = "${tradeSerialNo}"
//        push(ActCons.OrderPayInfoActivity, {
//            it.withSerializable("pay", pay)
//        })
        Asia5bPayUtils.skipPay(mActivity, pay) {
            if (it) {
                pop()
            }
        }
    }

    fun userCouponResult() {
        getOrderDetail()
    }

    override val isRegisterEventBus: Boolean
        get() = true

    /**
     * 选择地址回调
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onSelectAddressChange(event: SelectAddressChange) {
        val addressModel = event.addressModel
        //重置地址
        map["address_id"] = addressModel.addr_id
        map["region_id"] = addressModel.region_id
        map["city_id"] = addressModel.cityId
        //重置运输方式id
        map["goodscata_id"] = 0
        setTransferList(null)
        setAddressView(addressModel)
        getOrderDetail()
        //修改后台地址
        mViewModel.setAddress(map, addressModel)
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onPlaceSelectEvent(placeSelectEvent: PlaceSelectEvent) {
        when (placeSelectEvent.type) {
            //国际运输方式
            SelectType.intertrans -> {
                val select = placeSelectEvent.selectText as TransModel
                setTransferView(select)
                map["goodscata_id"] = select.id
                getOrderDetail()
            }
            //仓库
            SelectType.house -> {
                val select = placeSelectEvent.selectText as HouseModel
                setHouseView(select)
                setTransferList(null)
                map["house_id"] = select.id
                map["goodscata_id"] = 0
                getOrderDetail()
            }
            //支付
            SelectType.pay -> {
                val select = placeSelectEvent.selectText as OrderPayBean
                setPayView(select)
                map["payment_num"] = select.payId
                getOrderDetail()
            }
        }
    }
}